package com.yy.weixinpay.service.impl;



import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.yy.weixinpay.entity.PaymentInfo;
import com.yy.weixinpay.enums.PayType;
import com.yy.weixinpay.mapper.PaymentInfoMapper;
import com.yy.weixinpay.service.PaymentInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

@Service
@Slf4j
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    /**
     * 把支付日志放入数据库
     * @param plainText
     */
    @Override
    public void createPaymentInfo(String plainText) {
        log.info("支付日志:{}",plainText);
        //从明文里面拿数据
        Gson gson = new Gson();
        Map<String,Object> map = gson.fromJson(plainText, Map.class);
        //获取订单号
        Object orderNo = map.get("out_trade_no");
        //获取支付唯一编号
        Object transactionId = map.get("transaction_id");
        //获取支付类型
        Object tradeType = map.get("trade_type");
        //支付状态
        Object tradeState = map.get("trade_state");
        //实际支付总金额
        Map<String,Object> amount = (Map<String, Object>) map.get("amount");
        Integer payerTotal = ((Double) amount.get("payer_total")).intValue();
        //封装数据
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderNo((String) orderNo);
        paymentInfo.setPaymentType(PayType.WXPAY.getType());
        paymentInfo.setTradeType((String) tradeType);
        paymentInfo.setTransactionId((String) transactionId);
        paymentInfo.setTradeState((String) tradeState);
        paymentInfo.setPayerTotal(payerTotal);
        paymentInfo.setContent(plainText);
        baseMapper.insert(paymentInfo);
    }

    /**
     * 支付宝支付日志
     * @param params
     */
    @Override
    public void createPaymentInfoForAliPay(Map<String, String> params) {
        log.info("支付宝支付日志");
        String outTradeNo = params.get("out_trade_no");
        String tradeNo = params.get("trade_no");
        String status = params.get("trade_status");
        String totalAmount = params.get("total_amount");
        int totalFee = new BigDecimal(totalAmount).multiply(new BigDecimal(100)).intValue();
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderNo(outTradeNo);
        paymentInfo.setPaymentType(PayType.ALIPAY.getType());
        paymentInfo.setTradeType("电脑网站支付");
        paymentInfo.setTradeState(status);
        paymentInfo.setPayerTotal(totalFee);
        paymentInfo.setTransactionId(tradeNo);
        Gson gson = new Gson();
        String json = gson.toJson(params);
        paymentInfo.setContent(json);
        baseMapper.insert(paymentInfo);
    }
}
